<template>
  <div class="home-container">
    <Header />
    <div class="content">
      <!-- 搜索表单 -->
      <el-form :model="searchForm" ref="searchForm">
        <el-form-item label="绘本名称" prop="name">
          <el-input v-model="searchForm.name" placeholder="请输入绘本名称" />
        </el-form-item>
        <el-button type="primary" @click="searchBooks">搜索</el-button>
        <el-button type="success" style="margin-left: 10px" @click="addBookAll">新建绘本</el-button>
      </el-form>

      <!-- 绘本表格 -->
      <el-table :data="tableData" :loading="loading" style="width: 100%">
        <el-table-column prop="drawbook" label="绘本名称" width="300" />
		  <el-table-column prop="creator" label="创建者" width="300" />
        <el-table-column label="图片" width="250">
          <template #default="scope">
            <img :src="getImageUrl(scope.row.image_url)" alt="绘本图片" class="book-image" />
          </template>
        </el-table-column>
        <el-table-column prop="createtime" label="创建时间">
          <template #default="scope">
            {{ formatDate(scope.row.createtime) }}
          </template>
        </el-table-column>
        <el-table-column prop="modifytime" label="更新时间">
          <template #default="scope">
            {{ formatDate(scope.row.modifytime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" style="margin-right: 5px" @click="editBook(scope.$index)">编辑</el-button>
            <el-button type="danger" @click="deleteBook(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :total="total"
        :page-size="pageSize"
        @current-change="handlePageChange"
        v-if="total > pageSize"
      />

    </div>

    <!-- 编辑/新建绘本弹窗 -->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="isShow"
      size="600px"
      :before-close="handleDrawerClose"
    >
      <el-form :model="editForm" ref="editForm" :rules="formRules" label-width="100px">
        <el-form-item label="绘本名称" prop="name" style="width: 80%;">
          <el-input v-model="editForm.name" :disabled="disin" />
        </el-form-item>

        <el-form-item label="封面图片" prop="image_url">
          <el-upload
            ref="upload"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :before-upload="handleBeforeUpload"
            :file-list="fileList"
            :on-change="handleFileChange"
            :auto-upload="false"
            :limit="1"
            accept="image/*"
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog v-model="previewDialogVisible" size="large">
            <img :src="previewImage" alt="Preview" style="width: 100%;" />
          </el-dialog>
        </el-form-item>

        <!-- 内容编辑表格 -->
        <h3 style="padding-left: 50px;">绘本内容</h3>
        <el-table :data="editForm.content" border style="margin-left: 50px;width: 80%;">
          <el-table-column prop="content" label="内容" show-overflow-tooltip />
          
          <!-- 内容图片列 -->
          <el-table-column label="内容图片" width="150">
            <template #default="scope">
              <img :src="getImageUrl(scope.row.image)" alt="内容图片" class="content-image" />
            </template>
          </el-table-column>
          
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" style="margin-right: 5px" @click="editContent(scope.$index)">编辑</el-button>
              <el-button type="danger" size="small" @click="deleteContent(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="dashed" style="width: 80%; margin-left: 50px;margin-top: 20px;" @click="showAddContentModal">添加内容</el-button>
      </el-form>
      <div class="drawer-footer">
        <el-button type="primary" @click="saveBook" style="margin-left: 50px;margin-top: 20px;">保存</el-button>
        <el-button type="default" @click="isShow = false" style="margin-left:60px;margin-top: 20px;">取消</el-button>
      </div>
    </el-drawer>

    <!-- 添加内容弹窗 -->
    <el-dialog
      title="添加内容"
      :visible.sync="isAddContentModalVisible"
      @close="cancelAddContent"
    >
      <el-form :model="newContent" ref="newContentForm" :rules="contentRules">
        <el-form-item label="内容" prop="content">
          <el-input v-model="newContent.content" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        
        <!-- 新增图片上传区域 -->
        <el-form-item label="图片" prop="image">
          <el-upload
            ref="contentUpload"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleContentUploadSuccess"
            :before-upload="handleBeforeUpload"
            :file-list="contentFileList"
            :on-change="handleContentFileChange"
            :auto-upload="false"
            :limit="1"
            accept="image/*"
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog v-model="contentPreviewDialogVisible" size="large">
            <img :src="contentPreviewImage" alt="Preview" style="width: 100%;" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="addContentAll">确定</el-button>
        <el-button @click="cancelAddContent">取消</el-button>
      </div>
    </el-dialog>

    <Footer />
  </div>
</template>

<script>
import axios from 'axios';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import store from '../store';
import { formatTime, formatDate } from '@/utils/valid';
import { getDrawList, getDrawContentByName, getDrawContentByDrawbook, deleteDrawContent, addDraw, deleteDraw, addContent, createDrawtail, deleteDrawtail, getAllDrawtailByName } from '@/utils/api';
import { uploadUrl, url } from '@/utils/url';

export default {
  components: {
    Header,
    Footer
  },
  data() {
    return {
      contentFileList: [],  // 内容图片上传文件列表
      contentPreviewImage: null,  // 内容图片预览
      contentPreviewDialogVisible: false, // 内容图片预览对话框
      newContent: {
        content: '',
        image: ''  // 修改字段名
      },
      disin: false,
      loading: true,
      searchForm: { name: '' },
      columns: [
        { title: '绘本名称', key: 'drawbook', width: 300, align: 'center', sortable: true },
        { title: '图片', key: 'image', width: 250 },
        { title: '创建时间', key: 'createtime' },
        { title: '更新时间', key: 'modifytime' },
        { title: '操作', width: 200, slot: 'action', align: 'center' }
      ],
      contentColumns: [
        { title: '内容', key: 'content' },
        { title: '操作', slot: 'action' }
      ],
      data: '',
      tableData: [],
      total: 0,
      pageSize: 10,
      isShow: false,
      drawerTitle: '新建绘本',
      editForm: {
        id: 0,
        name: '',
        image_url: '',
        content: []
      },
      formRules: {
        name: [{ required: true, message: '绘本名称不能为空', trigger: 'blur' }]
      },
      contentRules: {
        content: [{ required: true, message: '内容不能为空', trigger: 'blur' }]
      },
      uploadUrl: uploadUrl,
      uploadHeaders: {
        'Authorization': `Bearer ${store.state.token}`
      },
      saving: false,
      currentEditIndex: -1,
      isAddContentModalVisible: false,
      fileList: [],
      previewImage: null,
      previewDialogVisible: false
    };
  },
  created() {
    this.loadBooks();
  },
  methods: {
    // 获取图片URL
    getImageUrl(relativePath) {
      if (!relativePath) return '';
      return relativePath.startsWith('http') ? relativePath : `${this.uploadUrl}${relativePath}`;
    },
    formatDate(time) {
      if (!time) return '';
      const date = new Date(time);
      return date.toLocaleString();
    },
    loadBooks() {
      this.loading = true;
      getDrawList()
        .then(res => {
          this.loading = false;
          if (res.code === 0) {
            this.tableData = res.data.map(item => ({
              id: item.id,
              drawbook: item.drawbook,
              image_url: item.image,
			  creator:item.creator,
              createtime: item.createtime,
              modifytime: item.modifytime
            }));
            this.total = res.data.length;
          } else {
            this.tableData = [];
            this.total = 0;
          }
        })
        .catch(err => {
          this.loading = false;
          this.$message.error('网络错误');
          console.error(err);
        });
    },
    searchBooks() {
      this.loading = true;
      const searchName = this.searchForm.name.trim();
      if (!searchName) {
        this.$message.warning('请输入绘本名称进行搜索');
        this.loading = false;
        return;
      }
      const params = { drawbook: searchName };
      getDrawContentByDrawbook(params)
        .then(res => {
          this.loading = false;
          if (res.code === 0) {
            if (res.data && res.data.length > 0) {
              this.tableData = [res.data[0]];
              this.total = 1;
            } else {
              this.tableData = [];
              this.total = 0;
              this.$message.info('未找到相关绘本');
            }
          } else {
            this.tableData = [];
            this.total = 0;
            this.$message.error(res.msg || '搜索失败');
          }
        })
        .catch(err => {
          this.loading = false;
          this.$message.error('网络错误');
          console.error(err);
        });
    },
    addBookAll() {
      this.disin = false;
      this.drawerTitle = '新建绘本';
      this.currentEditIndex = -1;
      this.editForm = {
        id: 0,
        name: '',
        image_url: '',
        content: []
      };
      this.isShow = true;
      this.$nextTick(() => {
        this.$refs.editForm.resetFields();
      });
    },
    editBook(index) {
      this.disin = true;
      this.drawerTitle = '编辑绘本';
      this.currentEditIndex = index;
      const book = this.tableData[index];
      this.editForm = {
        id: book.id,
        name: book.drawbook,
        image_url: book.image_url,
        content: book.content || []
      };
      this.getBookContent(book.drawbook);
      this.isShow = true;
    },
    editContent(index) {
      this.data = this.editForm.content[index].content;
      this.$router.push({ path: '/tail', query: { name: this.data } });
      localStorage.setItem('name', this.editForm.content[index].content);
    },
    getBookContent(name) {
      getDrawContentByName({ name: name })
        .then(res => {
          if (res.code === 0 && res.data && res.data.length > 0) {
            this.editForm.content = res.data.map(item => ({
              content: item.content,
              image: item.image  // 修改字段名
            }));
          } else {
            this.editForm.content = [];
          }
        })
        .catch(err => {
          console.error(err);
        });
    },
    deleteBook(index) {
  	
        const book = this.tableData[index];
        
        // 获取绘本内容
        getDrawContentByName({ name: book.drawbook })
          .then(res => {
            if (res.code === 0) {
              // 检查内容是否为空
              if (res.data && res.data.length > 0) {
                // 内容不为空，不能删除
                this.$message.error('该绘本包含内容，不能删除');
              } else {
                // 内容为空，可以删除
                this.$confirm('确定要删除该绘本吗？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                })
                  .then(() => {
                    deleteDraw({ 
  					  drawbook: book.drawbook ,
  					  creator:this.tableData[index].creator,
  					  image:this.tableData[index].image_url})
                      .then(res => {
                        if (res.code === 0) {
                          this.$message.success('删除成功');
                          this.tableData.splice(index, 1);
                          this.total = Math.max(this.total - 1, 0);
                        } else {
                          this.$message.error(res.msg || '删除失败');
                        }
                      })
                      .catch(err => {
                        this.$message.error('删除失败');
                        console.error(err);
                      });
                  })
                  .catch(() => {
                    this.$message.info('已取消删除');
                  });
              }
            } else {
              // 获取内容失败
              this.$message.error(res.msg || '获取绘本内容失败');
            }
          })
          .catch(err => {
            this.$message.error('网络错误');
            console.error(err);
          });
      },
    saveBook() {
      this.$refs.editForm.validate(valid => {
        if (!valid) return;
        
        this.saving = true;
        let formData = new FormData();
        formData.append('drawbook', this.editForm.name);
        formData.append('creator', this.$store.state.userInfo.data.userData.username);
        
        // 检查是否有文件被上传
        if (this.$refs.upload.uploadFiles.length > 0) {
          formData.append('file', this.$refs.upload.uploadFiles[0].raw);
        }

        if (this.editForm.id > 0) {
          // 编辑逻辑
     
          this.isShow = false;
        } else {
          // 新建逻辑
          axios.post(url + 'api/addDraw', formData)
            .then(response => {
			
              if (response.data.code == 0) {
                this.$message.success("创建成功");
                this.editForm.id = response.data.id;
                this.updateTableData();
                location.reload();
              } else {
                this.$message.error('创建失败123');
              }
            })
            .catch(error => {
              this.$message.error('创建失败');
              console.error(error);
            })
            .finally(() => {
              this.saving = false;
            });
        }
      });
    },
    updateTableData() {
      if (this.currentEditIndex >= 0 && this.currentEditIndex < this.tableData.length) {
        this.$set(this.tableData, this.currentEditIndex, {
          ...this.tableData[this.currentEditIndex],
          ...this.editForm
        });
      } else {
        this.tableData.unshift({ ...this.editForm });
        this.total++;
      }
      this.isShow = false;
    },
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 0) {
        this.editForm.image_url = response.data.path;
      } else {
        this.$message.error(response.msg || '上传失败');
      }
    },
   handleBeforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('只能上传图片文件');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片大小必须小于 2MB');
        return false;
      }
      return true;
    },
	 deleteContent(index) {
	      const contentItem = this.editForm.content[index];
	      if (!contentItem) {
	        this.$message.error('内容不存在');
	        return;
	      }
	      this.$confirm('确定要删除该内容吗？', '提示', {
	        confirmButtonText: '确定',
	        cancelButtonText: '取消',
	        type: 'warning'
	      })
	        .then(() => {
	          deleteDrawContent(
			  {
				  name: this.editForm.name, 
				  content: contentItem.content,
				  image:this.newContent.image
			  }
			
			)
	            .then(res => {
	              if (res.code === 0) {
	                this.$message.success('删除成功');
	                this.editForm.content.splice(index, 1);
	                this.getBookContent(this.editForm.name);
	              } else {
	                this.$message.error(res.msg || '删除失败');
	              }
	            })
	            .catch(err => {
	              this.$message.error('删除失败');
	              console.error(err);
	            });
	        })
	        .catch(() => {
	          this.$message.info('已取消删除');
	        });
	    },
    handleFileChange(file, fileList) {
      this.fileList = fileList;
      if (fileList.length > 0) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.previewImage = e.target.result;
        };
        reader.readAsDataURL(file.raw);
      }
    },
    showAddContentModal() {
      if (!this.editForm.name) {
        this.$message.warning('请先填写绘本名称');
        return;
      }
      this.newContent = { content: '', image: '' };
      this.isAddContentModalVisible = true;
    },
    // 添加内容逻辑修改
  // 添加内容逻辑
 // 添加内容逻辑
 addContentAll() {
   this.$refs.newContentForm.validate(valid => {
     if (!valid) return;
     
     // 创建 FormData 对象
     const formData = new FormData();
     
     // 添加内容文本
     formData.append('content', this.newContent.content);
     
     // 添加绘本名称
     formData.append('name', this.editForm.name);
     
     // 检查是否有文件被上传
     if (this.$refs.contentUpload.uploadFiles.length > 0) {
       // 添加图片文件
       formData.append('file', this.$refs.contentUpload.uploadFiles[0].raw);
     }
 
     // 新建逻辑
     axios.post(url + 'api/addContent', formData)
       .then(response => {
         if (response.data.code === 0) {
           this.$message.success("添加内容成功");
           this.getBookContent(this.editForm.name);
           this.cancelAddContent();
         } else {
           this.$message.error('添加内容失败: ' + response.data.msg);
         }
       })
       .catch(error => {
         this.$message.error('添加内容失败');
         console.error(error);
       });
   });
 },
    cancelAddContent() {
      this.isAddContentModalVisible = false;
    },
    handleDrawerClose(done) {
      if (this.saving) {
        this.$confirm('正在保存数据，是否要取消？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            done();
          })
          .catch(() => {
            // 取消关闭
          });
      } else {
        done();
      }
    },
    // 处理内容图片上传成功
  // 处理内容图片上传成功
  handleContentUploadSuccess(response, file, fileList) {
    if (response.code === 0) {
      // 确保图片路径已设置
      this.newContent.image = response.data.path;
    } else {
      this.$message.error(response.msg || '上传失败');
    }
  },
    // 处理内容图片上传前验证
    handleBeforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('只能上传图片文件');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片大小必须小于 2MB');
        return false;
      }
      return true;
    },
    // 处理内容图片文件变化
    handleContentFileChange(file, fileList) {
      this.contentFileList = fileList;
      if (fileList.length > 0) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.contentPreviewImage = e.target.result;
        };
        reader.readAsDataURL(file.raw);
      }
    }
  }
};
</script>

<style scoped>
.book-image {
  width: 80px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.content-image {
  width: 60px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}
</style>